package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import DGWeb.AppConstants;
import DGWeb.Model.*;
//import DGWeb.Servlets.messageInsert;
/**
 * Servlet implementation class replyInsert
 */
@WebServlet("/replyInsert")
public class replyInsert extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public replyInsert() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession UserSession = request.getSession();
		DateFormat dateFormat = new SimpleDateFormat(AppConstants.TimeFormat);
		InputStreamReader isr = new InputStreamReader(request.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		StringBuilder jsonFileContent = new StringBuilder();
		
		Context context = null;
		BasicDataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		
		//get currline
		String currNick = (String)UserSession.getAttribute("Nickname");
		//read line 
		jsonFileContent.append(br.readLine());
		Gson json = new Gson();
		Comments c = json.fromJson(jsonFileContent.toString(), Comments.class);
		int MsgId = c.getMsgId();
		String Text = c.getText();
		Text = "@"+GetMessageWriterNickname(MsgId)+ " "+ Text;
		String Time =dateFormat.format(Calendar.getInstance().getTime());
		
		
		try {
			context = new InitialContext();
			ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
			conn = ds.getConnection();
			stmt = conn.createStatement();
			String[] dt = AppConstants.COMMENTS_INSERT.split("//");
			String exec =dt[0]+MsgId+dt[1]+currNick+dt[2]+Text+dt[3]+Time+dt[4];
			
			stmt.executeUpdate(exec);
			
			conn.commit();
			stmt.close();
			conn.close();
			context.close();
			// to check if the comments has a new Topic
			messageInsert.AddTopics(Text,String.valueOf(MsgId));

		} catch (SQLException | NamingException e) {
			try {
				if (stmt != null)
					stmt.close();
				if (context != null)
					context.close();
				if ( conn != null )
					conn.close();
			} catch (NamingException|SQLException e1) {
				
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
			 		
			

		
	}
	
	private String GetMessageWriterNickname(int msgid)
	{
		String Nick="";
		Context context = null;
		BasicDataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		ResultSet res = null;
		
		try{
			context = new InitialContext();
			ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
			conn = ds.getConnection();
			//create Customers table
			stmt = conn.createStatement();	
			
			String exec = String.valueOf(msgid); 
			exec= AppConstants.GET_MESSAGE.replaceAll("//", exec );
			res = stmt.executeQuery(exec);
			res.next();
			Nick = res.getString(AppConstants.MESSAGES_WROTE_NICKNAME);
			
			res.close();
			stmt.close();
			conn.close();
			context.close();
		}catch (NamingException |SQLException  e) {
			
			try {
				if (res != null )
					res.close();
				if (stmt != null)
				stmt.close();
				if (context != null)
					context.close();
				if ( conn != null )
					conn.close();
			}catch (NamingException|SQLException e1) {
				
				e1.printStackTrace();
			}
		}
		
		return Nick;
	}

}
